<script setup>
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { getSearch } from '@/api/category.js'

const route = useRoute()
const keyword = ref(route.query.q || '')
const loading = ref(false)
const results = ref([])
const error = ref('')

async function search() {
  const res = await getSearch({
    keyword: route.query.q,
    page: 1,
    pageSize: 20,
    sortField: 'publishTime',
  })
}
// 页面加载时自动搜索
if (keyword.value) {
  search()
}

// 监听路由变化（如从其他页面跳转带参数）
watch(
  () => route.query.q,
  (newQ) => {
    keyword.value = newQ || ''
    if (keyword.value) search()
  },
)
</script>

<template>
  <div class="search-page">
    <div v-if="loading">正在搜索...</div>
    <div v-if="error" class="error">{{ error }}</div>
    <div v-if="results.length > 0" class="results">
      <div v-for="item in results" :key="item.id" class="result-item">
        <img :src="item.picture" alt="" />
        <div class="info">
          <p class="name">{{ item.name }}</p>
          <p class="desc">{{ item.desc }}</p>
          <p class="price">￥{{ item.price }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.search-page {
  max-width: 900px;
  margin: 30px auto;
  background: #fff;
  padding: 24px;
  border-radius: 8px;
}
.error {
  color: red;
  margin-bottom: 10px;
}
.results {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.result-item {
  width: 200px;
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 10px;
  background: #fafafa;
}
.result-item img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
}
.result-item .name {
  font-weight: bold;
  margin: 8px 0 4px 0;
}
.result-item .desc {
  color: #888;
  font-size: 14px;
  margin-bottom: 6px;
}
.result-item .price {
  color: #e4393c;
  font-size: 16px;
}
</style>
